<template>
  <v-app :dark="dark">
    <!-- 左侧导航条 -->
    <v-navigation-drawer
      :dark="dark"
      persistent
      :mini-variant="miniVariant"
      v-model="drawer"
      enable-resize-watcher
      fixed
      app
    >
      <v-toolbar flat class="transparent">
        <v-list class="pa-0">
          <v-list-tile avatar>
            <v-list-tile-avatar>
              <img :src="imageUrl">
            </v-list-tile-avatar>
            <v-list-tile-content>
              <v-list-tile-title>Auto Code</v-list-tile-title>
            </v-list-tile-content>
          </v-list-tile>
        </v-list>
      </v-toolbar>
      <v-divider/>
      <!-- 左侧菜单 -->
      <v-list class="pt-0" dense>
        <v-list-group
          v-model="item.active"
          v-for="item in items"
          :key="item.title"
          :prepend-icon="item.action"
          no-action
        >
          <!--一级菜单 -->
          <v-list-tile slot="activator">
            <v-list-tile-content>
              <v-list-tile-title>{{ item.title }}</v-list-tile-title>
            </v-list-tile-content>
          </v-list-tile>
          <!-- 二级菜单 -->
          <v-list-tile v-for="subItem in item.items" :key="subItem.title" :to="item.path + subItem.path">
            <v-list-tile-content>
              <v-list-tile-title>{{ subItem.title }}</v-list-tile-title>
            </v-list-tile-content>
            <v-list-tile-action>
              <v-icon>{{ subItem.action }}</v-icon>
            </v-list-tile-action>
          </v-list-tile>
        </v-list-group>
      </v-list>
    </v-navigation-drawer>
    <!-- 顶部工具条 -->
    <v-toolbar
      app
      dark
      :color="dark ? 'secondary' : 'primary'"
    >
      <!-- 隐藏左侧菜单的按钮-->
      <v-toolbar-side-icon @click.stop="drawer = !drawer"/>
      <!-- 收起左侧菜单的按钮-->
      <v-btn icon @click.stop="miniVariant = !miniVariant">
        <v-icon v-html="miniVariant ? 'chevron_right' : 'chevron_left'"/>
      </v-btn>
      <!-- 切换黑暗主题 -->
      <v-flex xs1>
        <v-switch
          :label="dark ? '暗黑' : '明亮'"
          v-model="dark"
          color="dark"
          hide-details
        />
      </v-flex>
      <!-- 顶部导航标题 -->
      <v-flex xs3></v-flex>
      <v-toolbar-title v-text="title"/>
      <v-spacer/>

      <h3>你好, {{this.$store.state.loginInfo.username}}</h3>
      <!-- 调色板 -->
      <v-btn icon @click.stop="dark = !dark">
        <v-icon>invert_colors</v-icon>
      </v-btn>
      <!-- 顶部导航用户菜单 -->
      <el-dropdown @command="handleCommand">
        <span class="el-dropdown-link">
        <v-btn icon>
          <v-icon>account_box</v-icon>
        </v-btn>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="modPwd">修改密码</el-dropdown-item>
          <el-dropdown-item command="modAva">更换头像</el-dropdown-item>
          <el-dropdown-item command="logout">登出系统</el-dropdown-item>
          <el-dropdown-item divided disabled>关于我们</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </v-toolbar>
<!-- 修改密码对话框-->
    <el-dialog
      title="修改密码"
      :visible.sync="modPwdVisible"
      width="30%"
      center>
      <el-form ref="modPwdForm" :model="modPwdForm" :rules="modPwdRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="modPwdForm.userName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="原密码" prop="oldPwd">
          <el-input v-model="modPwdForm.oldPwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="modPwdForm.newPwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="ackNewPwd">
          <el-input v-model="modPwdForm.ackNewPwd"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onModPwd('modPwdForm')">立即修改</el-button>
          <el-button @click="modPwdVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改头像对话框-->
    <el-dialog
      title="上传头像"
      :visible.sync="modAvaVisible"
      width="250px"
      center>
      <el-upload
        class="avatar-uploader"
        action="http://127.0.0.1:9001/user/avater/upload"
        :headers="headers"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="avaUrl" :src="avaUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        <div class="el-upload__tip" slot="tip">上传头像图片只能是 JPG 格式!</div>
        <div class="el-upload__tip" slot="tip">上传头像大小不超过2MB！</div>
      </el-upload>
    </el-dialog>

    <!--中间内容主体-->
    <v-content>
      <v-breadcrumbs>
        <v-icon slot="divider">chevron_right</v-icon>
        <v-breadcrumbs-item>{{item1}}</v-breadcrumbs-item>
        <v-breadcrumbs-item>{{item2}}</v-breadcrumbs-item>
      </v-breadcrumbs>
      <div>
        <!--定义一个路由锚点，Layout的子组件内容将在这里展示-->
        <router-view/>
      </div>
    </v-content>
  </v-app>
</template>

<script>
  // import menus from "../menu";

  export default {
    data() {
      return {
        authMenus:[], //授权的菜单列表
        dark: true,// 是否暗黑主题
        drawer: true,// 左侧导航是否隐藏
        miniVariant: false,// 左侧导航是否收起
        title: 'AutoCode Management System',// 顶部导航条名称,
        menuMap: {},
        modPwdVisible: false,
        modAvaVisible: false,
        imageUrl: '', //头像url 默认
        avaUrl: '',
        modPwdForm: {
          userName: this.$store.state.loginInfo.username,
          oldPwd: '',
          newPwd: '',
          ackNewPwd: '',
        },
        modPwdRules: {
          oldPwd:[
            { required: true, message: '原密码不允许为空', trigger: 'blur' }
          ],
          newPwd:[
            { required: true, message: '新密码不允许为空', trigger: 'blur' }
          ],
          ackNewPwd:[
            { required: true, message: '请确认新密码', trigger: 'blur' }
          ],
        }
      }
    },
    computed: {
      items() {
        return this.authMenus;
      },
      item1() {
        const arr = this.$route.path.split("/");
        return this.menuMap[arr[1]].name;
      },
      item2() {
        const arr = this.$route.path.split("/");
        return this.menuMap[arr[1]][arr[2]];
      },
      headers() {
        return {
          // Authentication: "Bearer " + (localStorage.token || "")
          Authentication: this.$store.state.token,
          RefreshToken: this.$store.state.refresh_token
        };
      }
    },
    name: 'App',
    watch: {},
    created() {
        //校验token是否存在
        if(!this.$store.state.refresh_token){
          this.$store.commit('del_token');
          this.$store.commit('del_refresh_token');
          this.$router.push("/login");
          return;
        }
        //根据登录名查询头像url
        this.$http.post("/user/getAvaUrl", this.$store.state.loginInfo.username).then(resp => {
          if(resp.data.data === '' || resp.data.data === null){
            this.imageUrl = 'http://127.0.0.1:9001/img/avater/default.jpg';
            return;
          }
          this.imageUrl = 'http://127.0.0.1:9001/img/avater/' + resp.data.data;
        });

        //根据登录名获取对应的授权的菜单列表
      this.$http.get("/menu/info/getMenuByLoginName?loginName=" + this.$store.state.loginInfo.username).then(resp => {
        if(resp.data.errCode === 200){
          this.authMenus = resp.data.data;
          //赋值menuMap
          this.authMenus.forEach(m => {
            console.log(m);
            const p1 = m.path.slice(1);
            this.menuMap[p1] = {name: m.title};
            m.items.forEach(i => {
              this.menuMap[p1][i.path.slice(1)] = i.title;
            })
          })

        }
      });

    },
    methods: {
      handleCommand(command){
        if(command === 'modPwd'){
          this.modPwdVisible = true;
        }else if(command === 'modAva'){
          this.modAvaVisible = true;
        }else if(command === 'logout'){
          this.$http.post("/user/logout").then(resp => {
            if(resp !== 'undefined' && resp !== '' && resp.data.errCode !== 200){
              console.log("success resp: " + resp);
              this.$message.error(resp.data.errCode + " : " + resp.data.errMsg);
              return;
            }
            this.$store.commit('del_token');
            this.$store.commit('del_refresh_token');
            this.$router.push('/login');
            this.$message.success("登出成功！");
          }).catch(err => {
            if(err === 'undefined' || err === ''){
              this.$store.commit('del_token');
              this.$store.commit('del_refresh_token');
              this.$router.push('/login');
              this.$message.success("登出成功！");
              return;
            }
            this.$message.error(err.status + " : " + err.error);
          });
        }
      },
      handleAvatarSuccess(res, file) {
        console.log("成功处理上传头像的返回：" + JSON.stringify(res));
        if(!res.data){
          this.$store.commit('del_token');
          this.$store.commit('del_refresh_token');
          this.$router.push('/login');
          return;
        }
        this.avaUrl = URL.createObjectURL(file.raw);
        this.$message.success("头像修改成功！");
        this.imageUrl = 'http://127.0.0.1:9001/img/avater/' + res.data;
        this.modAvaVisible = false;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      onModPwd(modPwdForm){
        this.$refs[modPwdForm].validate((valid) => {
          if (valid) {
            this.$http.post("/user/modPwd", this.modPwdForm).then(resp =>{
              console.log("修改密码响应：" + JSON.stringify(resp));
              if(resp.data.errCode === 200){
                this.$store.commit('del_token');
                this.$store.commit('del_refresh_token');
                this.$message.success("修改成功！请重新登录！");
                this.modPwdVisible = false;
                this.$router.replace('/login');
                return;
              }
              this.$message.error(resp.data.errCode + " : " + resp.data.errMsg);
            });
          } else {
            alert('密码修改失败!!');
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>
  .box {
    width: 90%;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
